<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            子数组问题都可以通过双重for循环，找出所有的子数组，时间复杂度On2

            思路2：定义一个变量sum，判断当前if(sum>=0),如果大于等于0，那么加上后面的nums[i]
            如果sum<0,那么让sum=nums[i]即可           
            */
            var maxSubArray = function (nums) {
                let result = -Infinity
                let sum = 0
                for (let i = 0; i < nums.length; i++) {
                    if (sum >= 0) {
                        sum += nums[i]
                    } else {
                        sum = nums[i]
                    }
                    result = Math.max(result, sum)
                }
                return result
            }
            console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
        </script>
    </body>
</html>
